//新增或编辑员工绩效计划
import { Form, Input, Button, message, Space, Table, Select,Modal,DatePicker,InputNumber,Pagination,Upload } from 'antd';
import type { UploadProps } from 'antd';
import { ReloadOutlined, SearchOutlined,PlusOutlined,DownloadOutlined,DeleteOutlined } from "@ant-design/icons";
import { useEffect, useState } from 'react';
import dayjs from 'dayjs';
import Router from "next/router"
import { http } from "@/utils/request";
import { useRouter } from 'next/router';
import { exportToXlsxBlob } from '@/pages/utils/exportToXlsx';
type TableRowSelection<T> = TableProps<T>['rowSelection'];
const addOrEditStaffPlan = () =>{
  const router = useRouter();
  const { id, title } = router.query;
  const [form] = Form.useForm();
  const [addForm] = Form.useForm();
  const [data,setData] = useState([]);
  const [addModal,setAddModal] = useState(false);
  const [indicatorData,setIndicatorData] = useState([]);
  const [option,setOption] = useState([]);
  const [pageNum,setPageNum] = useState(1);
  const [pageSize,setPageSize] = useState(10);
  const [total,setTotal] = useState();
  const [addSelectedRowKeys, setAddSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedRows,setSelectedRows] = useState<React.Key[]>([]);
  const columns: TableColumnsType<TableDataType> = [
    {
      title: "序号",
      key: "index",
			align:'center',
      width:80,
      render: (_text, _record, index) => {
        return index + 1
      }
    },
    {
      title: "指标编码",
      dataIndex: "code",
			align:'center',
      width:100,
    },
    {
      title: "指标类型",
      dataIndex: "targetTypeName",
			align:'center',
      width:100,
    },
    {
      title: "指标名称",
      dataIndex: "name",
			align:'center',
      width:150,
    },
    {
      title: "权重(%)",
      dataIndex: "targetWeight",
			align:'center',
      width:100,
      render: (_,record) => {
        return (
          <>
          <InputNumber placeholder="请输入权重" value={record.targetWeight} min={0} max={100} onChange={(value) => {
            const newDataSource = data.map((item) => {
              if(item.targetId == record.targetId){
                item.targetWeight = value
                return item;
              }
              return item;
            });
            setData(newDataSource);
          }}/>
          </>
        )
      }
    },
    {
      title: "指标定义",
      dataIndex: "content",
			align:'center',
      width:150,
    },
    {
      title: "考核标准",
      dataIndex: "standard",
			align:'center',
      width:150,
    },
  ];
  const indicatorColumns: TableColumnsType<TableDataType> = [
    {
      title: "指标编码",
      dataIndex: "code",
			align:'center',
      width:100,
    },
    {
      title: "指标类型",
      dataIndex: "targetTypeName",
			align:'center',
      width:120,
    },
    {
      title: "指标名称",
      dataIndex: "name",
			align:'center',
      width:150,
    },
    {
      title: "最高分",
      dataIndex: "maxScore",
			align:'center',
      width:100,
    },
    {
      title: "最低分",
      dataIndex: "minScore",
			align:'center',
      width:100,
    },
    {
      title: "指标定义",
      dataIndex: "content",
			align:'center',
      width:150,
    },
    {
      title: "考评标准",
      dataIndex: "standard",
			align:'center',
      width:150,
    },
  ]
  const onAddSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setAddSelectedRowKeys(newSelectedRowKeys);
  };
  const addRowSelection: TableRowSelection<DataType> = {
    addSelectedRowKeys,
    onChange: onAddSelectChange,
  };
  const onSelectChange = (newSelectedRowKeys: React.Key[], newSelectedRows) => {
    setSelectedRows(newSelectedRows)
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const changeYear = (date, dateString) =>{
    console.log(date, dateString);
    form.setFieldsValue({planBeginTime:dayjs(dateString+'-01-01', 'YYYY-MM-DD'),planEndTime:dayjs(dateString+'-12-31', 'YYYY-MM-DD')})
  }
  const addAssessmentDetails = () =>{
    getTypeList();
    getList();
    setAddModal(true);
  }
  const delAssessmentDetails = () =>{
    // 创建一个新的数组，避免直接修改原始数组
    const updatedData = data.filter(dataItem => 
      !addSelectedRowKeys.includes(String(dataItem.targetId))
    );
    const newSelectedRowKeys = selectedRowKeys.filter(dataItem => 
      !addSelectedRowKeys.includes(String(dataItem))
    );
    const newSelectedRows = selectedRows.filter(dataItem => 
      !addSelectedRowKeys.includes(String(dataItem.targetId))
    );
    // 更新状态，传递新数组
    setData(updatedData);
    setSelectedRowKeys(newSelectedRowKeys);
    setSelectedRows(newSelectedRows);
  }
  const handleOk = ()=>{
    setAddModal(false);
    const arr = JSON.parse(JSON.stringify(selectedRows))
    arr.map(item=>{
      item.targetId = item.id
      item.targetCode = item.code
      item.targetName = item.name
      item.targetContent = item.content
      item.targetWeight = 0
      delete item.id
    })
    setData(arr);
    setAddSelectedRowKeys([])
  }
  const handleCancel = ()=>{
    setAddModal(false);
  }
  // 模板下载
  const downloadTemp = async() =>{
    try {
      const res = await http.post({
        url:'/pmEvaluPlan/exportTemplate',
        responseType: 'arraybuffer',
        data:{type:1}
      })
      if(res.code==200){
        exportToXlsxBlob(res,'考核明细导入模板')
        message.success('模板开始下载!');
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  // 指标导入
  const uploadprops: UploadProps = {
    // 这里我们只接受excel2007以后版本的文件，accept就是指定文件选择框的文件类型
    accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    name: 'file',
    action: '/api/performance/pmEvaluPlan/importExcel',
    headers: {
      'X-YUJIA-Principal':"%7B%22divs%22%3A%22%22%2C%22enabled%22%3Atrue%2C%22accountNonExpired%22%3Atrue%2C%22credentialsNonExpired%22%3Atrue%2C%22accountNonLocked%22%3Atrue%2C%22manageOrgId%22%3Anull%2C%22orgCode%22%3A%22%22%2C%22orgName%22%3A%22%22%2C%22jobCode%22%3A%22%22%2C%22jobId%22%3Anull%2C%22name%22%3A%22%E5%B9%B3%E5%8F%B0%E7%AE%A1%E7%90%86%E5%91%98%22%2C%22jobCodes%22%3A%22%22%2C%22roleCodes%22%3A%22'PlatformManager'%22%2C%22subject%22%3Anull%2C%22issuer%22%3Anull%2C%22audience%22%3Anull%2C%22authenticatedAt%22%3Anull%2C%22nonce%22%3Anull%2C%22authenticationContextClass%22%3Anull%2C%22authenticationMethods%22%3Anull%2C%22authorizedParty%22%3Anull%2C%22accessTokenHash%22%3Anull%2C%22authorizationCodeHash%22%3Anull%2C%22issuedAt%22%3Anull%2C%22expiresAt%22%3Anull%2C%22zoneInfo%22%3Anull%2C%22locale%22%3Anull%2C%22fullName%22%3Anull%2C%22email%22%3Anull%2C%22givenName%22%3Anull%2C%22familyName%22%3Anull%2C%22profile%22%3Anull%2C%22nickName%22%3Anull%2C%22preferredUsername%22%3Anull%2C%22picture%22%3Anull%2C%22website%22%3Anull%2C%22emailVerified%22%3Anull%2C%22gender%22%3Anull%2C%22birthdate%22%3Anull%2C%22phoneNumber%22%3Anull%2C%22phoneNumberVerified%22%3Anull%2C%22username%22%3A%22platformAdmin%22%2C%22address%22%3A%7B%22formatted%22%3Anull%2C%22streetAddress%22%3Anull%2C%22locality%22%3Anull%2C%22region%22%3Anull%2C%22postalCode%22%3Anull%2C%22country%22%3Anull%2C%22%40class%22%3A%22org.springframework.security.oauth2.core.oidc.DefaultAddressStandardClaim%22%7D%2C%22id%22%3A2%2C%22updatedAt%22%3Anull%2C%22middleName%22%3Anull%2C%22jobName%22%3A%22%22%2C%22orgId%22%3Anull%2C%22password%22%3Anull%7D",
        'x-yujia-app-id':"app1",
        'x-yujia-current-app':'{"appId":"app1","id":2}',
    },
    showUploadList:false,
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success('导入成功！');
        console.log(info);
        
        // getList();
        // todo 导入成功，回显导入数据
      } else if (info.file.status === 'error') {
        message.error('导入失败！');
      }
    },
  };
  const onSearchHandler = () => {
    getList();
  };
  const onResetHandler = () => {
    addForm.resetFields();
    getList();
  };
  //获取指标类型
  const getTypeList = async()=>{
    try {
      const res = await http.get({
        url:'/pmPerformTargetType/qryList'
      })
      if(res.code==200){
        setOption(res.rows.map(item=>({value:item.id,label:item.name})))
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log(errorInfo);
    }
  }
  //查询指标接口
  const getList = async() =>{
    try {
      const res = await http.get({
        url:'/pmPerformTargetItem/qryList',
        params:{
          itemName:addForm.getFieldValue().itemName,
          targetTypeId:addForm.getFieldValue().targetTypeId,
          pageNum:pageNum,
          pageSize:pageSize,
          manageType:'2',
        }
      })
      setIndicatorData(res.rows);
      setTotal(res.total);
    } catch (errorInfo) {
      console.log(errorInfo);
    }
  }
  //修改页码或分页大小
  const changePagination = async (page: number, size: number)=>{
    setPageNum(page);
    if(size!==pageSize){
      setPageNum(1);
    }
    setPageSize(size);
  }
  const save = async() =>{
    try {
      const values = await form.validateFields();
      values.evaluYear = dayjs(values.evaluYear).format('YYYY');
      values.planBeginTime = dayjs(values.planBeginTime).format('YYYY-MM-DD');
      values.planEndTime = dayjs(values.planEndTime).format('YYYY-MM-DD');
      values.itemList=data
      values.addOrSubmit = false;
      let totalWeight = 0
      values.itemList.map(item=>{
        totalWeight +=item.targetWeight
      })
      if(totalWeight!==100){
        message.error('指标权重总值必须等于100%，请重新修改各指标权重！');
        return
      }
      if(title=='新增员工绩效计划'){
        addSave(values);
      }else{
        editSave(values);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  const submit = async() =>{
    try {
      const values = await form.validateFields();
      values.evaluYear = dayjs(values.evaluYear).format('YYYY');
      values.planBeginTime = dayjs(values.planBeginTime).format('YYYY-MM-DD');
      values.planEndTime = dayjs(values.planEndTime).format('YYYY-MM-DD');
      values.itemList = data
      values.addOrSubmit = true;
      let totalWeight = 0
      values.itemList.map(item=>{
        totalWeight +=item.targetWeight
      })
      if(totalWeight>100){
        message.error('指标权重总值大于100%，请重新修改各指标权重！');
        return
      }
      
      if(title=='新增员工绩效计划'){
        addSave(values);
      }else{
        editSave(values);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  //新增接口
  const addSave = async(data:object) =>{
    try {
      const res = await http.post({
        url:'/pmEvaluPlan/add',
        data:{...data,evaluType:'20',deptLeaderId:1,deptLeader:'总监1',evaluObjectId:2},//todo人员id暂时写死，后面去用户信息接口获取
      })
      if(res.code == 200){
        message.success('员工计划新增成功!');
        Router.push('/performancePlan/staff');
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  //编辑接口
  const editSave = async(data:object) =>{
    try {
      
      data.itemList.map(item=>{
        item.targetWeight = Number(item.targetWeight);
      })
      const res = await http.post({
        url:'/pmEvaluPlan/update',
        data:{id,...data,evaluType:'20',deptLeaderId:1,deptLeader:'总监1',evaluObjectId:2}
      })
      if(res.code == 200){
        message.success('员工计划修改成功!');
        Router.push('/performancePlan/staff');
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  // 获取详情
  const getDetailInfo = async()=>{
    const res = await http.get({
      url:'/pmEvaluPlan/qryById',
      params:{planId:id}
    })
    if(res.code==200){
      const data = JSON.parse(JSON.stringify(res.data));
      data.planBeginTime = dayjs(data.planBeginTime, 'YYYY-MM-DD');
      data.planEndTime = dayjs(data.planEndTime, 'YYYY-MM-DD');
      data.evaluYear = dayjs(data.evaluYear, 'YYYY');
      form.setFieldsValue(data);
      const selectIdList = []
      data.changeItemList.map(item=>{
        item.code = item.targetCode
        item.name = item.targetName
        item.content = item.targetContent
        delete item.id;
        selectIdList.push(item.targetId)
      })
      setData(data.changeItemList);
      setSelectedRowKeys(selectIdList);
    }else{
      message.error(res.msg);
    }
  }
  useEffect(()=>{
    form.setFieldsValue({evaluTypeName:'个人'})
    //todo 等能够获取到用户信息的时候，获取账号的用户信息并回显
    if(title=='新增员工绩效计划'){
      form.setFieldsValue({evaluObject:'张三'})
    }else{
      getDetailInfo();
    }
  },[])
  return(
    <div>
      <div className={'title'}>{title}</div>
      <Form
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        form={form}
        layout={'inline'}
        autoComplete="off"
      >
        <Form.Item name="planCode" label={'计划编号'} style={{width:'30%',marginBottom:'20px'}}>
          <Input disabled/>
        </Form.Item>
        <Form.Item name="planName" label={'计划名称'} rules={[{ required: true, message: '请输入计划名称!' }]} style={{width:'30%',marginBottom:'20px'}}>
          <Input placeholder="请输入计划名称" />
        </Form.Item>
        <Form.Item name="evaluYear" label={'计划考核年度'} rules={[{ required: true, message: '请选择计划考核年度!' }]} style={{width:'30%',marginBottom:'20px'}}>
          <DatePicker picker="year" placeholder="请选择计划考核年度" onChange={changeYear} style={{width:'100%'}}/>
        </Form.Item>
        <Form.Item name="evaluFrequency" label={'计划频次'} style={{width:'30%',marginBottom:'20px'}}>
          <Select placeholder="请选择计划频次" options={[
            { value: '10', label: '年度' },
            { value: '20', label: '季度' },
            { value: '30', label: '月度' },
          ]} />
        </Form.Item>
        <Form.Item name="planBeginTime" label={'计划开始日期'} rules={[{ required: true, message: '请选择计划开始日期!' }]} style={{width:'30%',marginBottom:'20px'}}>
          <DatePicker placeholder="请选择计划开始日期" style={{width:'100%'}} disabled/>
        </Form.Item>
        <Form.Item name="planEndTime" label={'计划结束日期'} rules={[{ required: true, message: '请选择计划结束日期!' }]} style={{width:'30%',marginBottom:'20px'}}>
          <DatePicker placeholder="请选择计划结束日期" style={{width:'100%'}} disabled/>
        </Form.Item>
        <Form.Item name="evaluObject" label={'被考核人'} style={{width:'30%',marginBottom:'20px'}}>
          <Input placeholder="请输入被考核人" disabled/>
        </Form.Item>
        <Form.Item name="evaluTypeName" label={'考核类型'} style={{width:'30%',marginBottom:'20px'}}>
          <Input placeholder="请输入考核类型" disabled/>
        </Form.Item>
        <Form.Item name="fractionMax" label={'总分上限'} rules={[{ required: true, message: '请输入总分上限!' }]} style={{width:'30%',marginBottom:'20px'}}>
          <InputNumber placeholder="请输入总分上限" min={1} style={{width:'100%'}}/>
        </Form.Item>
      </Form>
      <div className={'title'}>考核明细列表</div>
      <Space style={{display:'flex',justifyContent:' flex-end'}}>
        <Button icon={<DownloadOutlined />} onClick={downloadTemp}>
          下载模板
        </Button>
        <Upload {...uploadprops}>
          <Button icon={<DownloadOutlined />}>
            导入
          </Button>
        </Upload>
        <Button type="primary" icon={<PlusOutlined />} onClick={addAssessmentDetails}>
          新增
        </Button>
        <Button type="primary" danger icon={<DeleteOutlined />} onClick={delAssessmentDetails}>
          删除
        </Button>
      </Space>
      <Table
        style={{marginTop:'20px'}}
        dataSource={data}
        bordered
        columns={columns}
        pagination={false}
        rowKey={(record) => `${record.targetId}`}
        rowSelection={addRowSelection}
      ></Table>
      <Space style={{display:'flex',justifyContent:' flex-end',marginTop:'20px'}}>
        <Button onClick={()=>{Router.push('/performancePlan/staff')}}>
          返回
        </Button>
        <Button onClick={save}>
          保存
        </Button>
        <Button type="primary" onClick={submit}>
          提交
        </Button>
      </Space>
      {/* 新增考核明细弹窗 */}
      <Modal title={'新增考核明细'} open={addModal} onCancel={handleCancel} width={880} footer={[
        <Button key="back" onClick={handleCancel}>
          返回
        </Button>,
        <Button key="submit" htmlType="submit" type="primary" onClick={handleOk}>
          保存
        </Button>,]}
      >
        <Form
          form={addForm}
          layout={'inline'}
          autoComplete="off"
        >
          <Form.Item name="itemName" label={'指标名称'}>
            <Input placeholder="请输入指标名称" />
          </Form.Item>
          <Form.Item name="targetTypeId" label={'指标类型'}>
            <Select placeholder="请选择指标类型" options={option} />
          </Form.Item>
          <Form.Item className={'search-form-button !flex-1 text-right'}>
            <Space>
              <Button type="primary" icon={<SearchOutlined />} onClick={onSearchHandler}>
                查询
              </Button>
              <Button icon={<ReloadOutlined />} onClick={onResetHandler}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
        <Table
          // scroll={{ x: 1300 }}
          style={{marginTop:'20px'}}
          dataSource={indicatorData}
          bordered
          columns={indicatorColumns}
          pagination={false}
          rowKey={(record) => `${record.id}`}
          rowSelection={rowSelection}
        ></Table>
        <Pagination
          className={'m-[20px] text-end'}
          current={pageNum}
          pageSize={pageSize}
          total={total}
          align="end"
          showSizeChanger
          showQuickJumper
          showTotal={(total) => `共 ${total} 条`}
          onChange={changePagination}
        />
      </Modal>
    </div>
  )
}
export default addOrEditStaffPlan;